package com.changgou.seckill.timer;

import com.changgou.entity.DateUtil;
import com.changgou.entity.SystemConstants;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsPushTask {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 测试每5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void loadGoodsPushRedis() {
        System.out.println("task todo");
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            // extName
            String ext = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYYMMDDHH);
            // 根据时间段查询对应的商品数据
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            // 审核通过的
            criteria.andEqualTo("status", "1");
            // 库存大于0的 > 0
            criteria.andGreaterThan("stockCount", 0);
            // >=startTime
            criteria.andGreaterThanOrEqualTo("startTime", dateMenu);
            // < endTime
            criteria.andLessThan("endTime", DateUtil.addDateHour(dateMenu, 2));

            // 排除id已存在redis中的数据,防止数据被重置, 比如说有人买了秒杀里的商品,库存应该减少了,定时任务还在执行,然后该商品的库存又会被重置到原来的
            Set keys = redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + ext).keys();
            if (keys != null && keys.size() > 0) {
                criteria.andNotIn("id", keys);
            }

            // 查询数据
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            for (SeckillGoods seckillGood : seckillGoods) {
                // 商品压入redis中  SeckillGoods_2020052508, id, seckillgood
                redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX+ext).put(seckillGood.getId(), seckillGood);
                // 设置过期时间
                redisTemplate.expireAt(SystemConstants.SEC_KILL_GOODS_PREFIX+ext, DateUtil.addDateHour(dateMenu, 2));
            }
        }
    }

}